package zeno.project.springboot.exception;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import zeno.project.springboot.entity.base.JsonResult;

/**
 * 学习全局异常处理
 * 注解@ControllerAdvice可拦截所有【系统】异常
 * 且异常拦截是根据异常定义顺序拦截的，Exception异常作为异常父类，放在最后拦截一劳永逸
 */
@ControllerAdvice
@ResponseBody
public class GlobalExceptionHandler {
    // 打印log
    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    /**
     * 缺少请求参数异常
     * @param ex HttpMessageNotReadableException
     * @return ex
     */
    @ExceptionHandler(MissingServletRequestParameterException.class)
    @ResponseStatus(value = HttpStatus.BAD_REQUEST)
    public Object handleHttpMessageNotReadableException(
            MissingServletRequestParameterException ex) {
        logger.error("缺少请求参数，{}", ex.getMessage());
        return new JsonResult<BusinessMsgEnum>("400", ex.getMessage());
    }

    /**
     * 空指针异常
     * @param ex NullPointerException
     * @return ex
     */
    @ExceptionHandler(NullPointerException.class)
    @ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
    public Object handleTypeMismatchException(NullPointerException ex) {
        logger.error("空指针异常，{}", ex.getMessage());
        return new JsonResult<BusinessMsgEnum>("500", "空指针异常了");
    }

    /**
     * 系统异常 预期以外异常
     * @param ex ex
     * @return ex
     */
    @ExceptionHandler(Exception.class)
    @ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
    public Object handleUnexpectedServer(Exception ex) {
        logger.error("系统异常：", ex);
        return new JsonResult<BusinessMsgEnum>("500", "系统发生异常，请联系管理员");
    }
}
